package com.scarecrow.olga.util.logging {
	
	import flash.utils.getTimer;
	/**
	 * ...
	 * @author Santiago.J.Elizalde
	 */
	public class Profiler {
		
		private static const HEADER:String = "---------------------- PROFILER INFO --------------------------"
		private static const FOOTER:String = "---------------------------------------------------------------"
		
		private static var startStamps:Object;
		
		private static var acumTime:Object;
		private static var acumCalls:Object;
		
		public function Profiler() {
			
		}
		
		public static function start(taskKey:String):void {
			if (!startStamps) startStamps = new Object();
			if (!acumTime) acumTime = new Object();
			if (!acumCalls) acumCalls = new Object();
			
			if (startStamps[taskKey]) {
				throw new Error("profiler.start(): the started task '" + taskKey + "' was already active.");
			}
			
			startStamps[taskKey] = getTimer();
			if (!acumTime[taskKey]) {
				acumTime[taskKey] = 0;
			}
			if (!acumCalls[taskKey]) {
				acumCalls[taskKey] = 1;
			} else {
				acumCalls[taskKey]++;
			}
		}
		
		public static function end(taskKey:String):void {
			if (startStamps[taskKey]) {
				acumTime[taskKey] += getTimer() - startStamps[taskKey];
				delete startStamps[taskKey];
			}
		}
		
		public static function dump(taskKey:String):String {
			if (!acumTime) return "[INFO] Profiler: no data";
			var result:String = HEADER + "\n";
			result += "-[" + taskKey + "] TIME: " + acumTime[taskKey] + "ms [" + acumCalls[taskKey] + " calls][" + (acumTime[taskKey]/acumCalls[taskKey]) + "ms per call]";
			result += "\n";
			result += FOOTER;
			return result;
		}
		
		public static function dumpAll():String {
			if (!acumTime) return "[INFO] Profiler: no data";
			var result:String = HEADER + "\n";
			for (var task:String in acumTime) {
				var avg:Number = acumTime[task] / acumCalls[task];
				
				result += "-[" + task + "] TIME: " + acumTime[task] + " [" + acumCalls[task] + " calls][" + avg.toPrecision(4) + "ms per call]";
				result += "\n";
			}
			result += FOOTER;
			return result;
		}
		
		public static function reset():void {
			for (var name:String in acumTime) {
				acumCalls[name] = 0;
				acumTime[name] = 0;
			}
		}
	}

}